package com.ming.stringstudy.feedbacksystem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ming.stringstudy.feedbacksystem.entity.Permission;
import com.ming.stringstudy.feedbacksystem.mapper.PermissionMapper;
import com.ming.stringstudy.feedbacksystem.mapper.RolePermissionMapper;
import com.ming.stringstudy.feedbacksystem.pojo.PageBean;
import com.ming.stringstudy.feedbacksystem.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author aming
 * @since 2025-01-19
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageBean<Permission> page(Integer page, Integer pageSize, Permission permission) {
        PageHelper.startPage(page, pageSize);

        List<Permission> permissionList = permissionMapper.findByAttributes(permission);

        PageInfo<Permission> p = new PageInfo<>(permissionList);
        PageBean pageBean = new PageBean(p.getTotal(), p.getList());
        return pageBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addPermission(Permission permission) {
        if (permission.getPermissionName() == null || permission.getPermissionName().equals("")) {
            return 0;
        }
        if (permissionMapper.findAllByPermissionName(permission.getPermissionName()) != null){
            return 0;
        }

        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());

        int result = permissionMapper.insert(permission);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePermission(Permission permission) {
        if (permissionMapper.findAllByPermissionName(permission.getPermissionName()) != null){
            return 0;
        }
        permission.setUpdateTime(LocalDateTime.now());
        int result = permissionMapper.updateById(permission);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePermission(List<Integer> ids) {
        int result = permissionMapper.deleteBatchIds(ids);
        rolePermissionMapper.deleteRolePermissionByDeletedPermissionId(ids);
        return result;
    }
}
